/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.service.organization.impl;

import com.google.common.base.Strings;
import com.je.common.auth.impl.Department;
import com.je.common.auth.impl.RealOrganization;
import com.je.common.auth.impl.RealOrganizationUser;
import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.exception.AccountException;
import com.je.rbac.service.organization.OrgType;
import com.je.rbac.service.organization.RbacOrganizationService;
import com.je.rbac.service.organization.RbacRealOrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RbacRealOrganizationServiceImpl implements RbacRealOrganizationService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private RbacOrganizationService rbacOrganizationService;

    @Override
    public void fillRealUser(String orgId, String realId, RealOrganizationUser realUser) throws AccountException {
        /*
         * 找到映射资源表，查找到DynaBean，执行真实用户parse
         * */
        DynaBean orgBean = rbacOrganizationService.findById(orgId);
        if(orgBean == null){
            throw new AccountException("Can't find the org mapping from the database!");
        }

        //获取到映射的资源表和资源表主键
        String tableCode = orgBean.getStr("ORG_RESOURCETABLE_CODE");
        String tableIdCode = orgBean.getStr("ORG_FIELD_PK");
        if(Strings.isNullOrEmpty(tableCode) || Strings.isNullOrEmpty(tableIdCode)){
            throw new AccountException("Can't find the tableCode or pk code from the org mapping!");
        }

        //获取映射字段，账号名称、账号编码、账号手机、账号邮箱、账号头像
        String accountNameField = orgBean.getStr("ORG_ACCOUNT_NAME");
        String accountCodeField = orgBean.getStr("ORG_ACCOUNT_CODE");
        String accountPhoneField = orgBean.getStr("ORG_ACCOUNT_PHONE");
        String accountEmailField = orgBean.getStr("ORG_ACCOUNT_MAIL");
        String accountAvatarField = orgBean.getStr("ORG_ACCOUNT_AVATAR");

        if(Strings.isNullOrEmpty(accountNameField) || Strings.isNullOrEmpty(accountCodeField)
                || Strings.isNullOrEmpty(accountPhoneField) || Strings.isNullOrEmpty(accountEmailField)
                || Strings.isNullOrEmpty(accountAvatarField)){
            throw new AccountException("Can't find the mapping fields from the org mapping!");
        }

        //获取到bean进行parse，执行返回
        DynaBean userBean = metaService.selectOne(tableCode, ConditionsWrapper.builder().eq(tableIdCode,realId));
        realUser.parse(userBean.getValues());
        if (!OrgType.DEPARTMENT_ORG_ID.getCode().equals(orgBean.getStr("JE_RBAC_ORG_ID"))) {
            realUser.setId(userBean.getStr(tableIdCode));
            realUser.setName(userBean.getStr(accountNameField));
            realUser.setCode(userBean.getStr(accountCodeField));
            realUser.setAvatar(userBean.getStr(accountAvatarField));
            realUser.setPhone(userBean.getStr(accountPhoneField));
            realUser.setEmail(userBean.getStr(accountEmailField));
            RealOrganization organization = new Department();
            organization.setId(orgBean.getStr("JE_RBAC_ORG_ID"));
            organization.setName(orgBean.getStr("ORG_NAME"));
            organization.setCode(orgBean.getStr("ORG_CODE"));
            realUser.setOrganization(organization);
        }

    }

    @Override
    public void fillOrganization(String realOrgId, RealOrganization realOrganization) throws AccountException {
        /**
         * 1. 根据机构模型的资源表，和主键信息；
         * 2. 获取真实的机构DynaBean；
         * 3. 查找机构的关联权限集合；
         * 4. 进行解析。
         */
        String tableCodeField = realOrganization.getTableCode();
        String tablePkField = realOrganization.getTablePkCode();
        if(Strings.isNullOrEmpty(tableCodeField) || Strings.isNullOrEmpty(tablePkField)){
            throw new AccountException("Can't find the tableCode or pk code from the org model!");
        }
        //获取机构Bean
        DynaBean orgRealBean = metaService.selectOne(tableCodeField,ConditionsWrapper.builder().eq(tablePkField,realOrgId));
        if(orgRealBean == null){
            throw new AccountException("Can't find the real org from the database!");
        }
        //进行解析
        realOrganization.parse(orgRealBean.getValues());
    }

}
